package com.guangaiboen.attendance.core.dispatcher.executor;

import com.alibaba.fastjson.JSON;
import com.guangaiboen.attendance.core.dispatcher.constants.RequestTypes;
import com.guangaiboen.attendance.core.dispatcher.context.DispatcherContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import java.nio.charset.Charset;


/**
 * Json请求
 * @param <T> 返回类型
 */
public abstract  class JsonHttpDispatcherExecutor<T > extends PostHttpDispatcherExecutor<T> {

    private static final String CONTENT_TYPE = "application/json";

    @Override
    protected StringEntity createEntity(String url, DispatcherContext dispatcherContext) {
        Object dispatcherParameters = getDispatcherParameters(url,dispatcherContext);
        String jsonBody = JSON.toJSONString(dispatcherParameters);
        return new StringEntity(jsonBody,getContentType());
    }

    protected abstract Object getDispatcherParameters(String url, DispatcherContext dispatcherContext);

    public Charset getCharset(){
        return DEFAULT_CHARSET;
    }

    public ContentType getContentType(){
        return ContentType.create(CONTENT_TYPE,getCharset());
    }

    @Override
    protected String getRequestTypes() {
        return RequestTypes.JSON.getRequestCode();
    }

}
